﻿package 
{
	import flash.display.Sprite;	
	import flash.events.Event;	
	import flash.events.KeyboardEvent;
	import flash.ui.Keyboard;
	import flash.text.TextField;	

	/*
	 * coded by moka 2009 / 08/ 01 
	 * name : moka's spriteControl
	 * blog : http://designplusplus.blogspot.com/
	 */
	
	public class Main extends Sprite 
	{		
		private var sp:Sprite = new Sprite();
		private var state:Array = new Array(0, 0, 0, 0); //save key press status (up,down,left,right)	
		private	var speed:Number = 2;
		
		public function Main():void 
		{			
			// stage setting
			stage.scaleMode = "noScale";	

			// create character			
			sp.graphics.lineStyle(1, 0xFFFFFF);
			sp.graphics.drawCircle(320, 240, 20);
			addChild(sp);
			
			// event registration
			stage.addEventListener(Event.ENTER_FRAME, onProcess);	
			stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
			stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
			stage.focus = this;
			
			// Moka's work 2009
			(addChild(new TextField()) as TextField).htmlText = "<font color='#FFFFFF'>Moka's work 2009</font>";
		}		
		
		
		private function onKeyUp(e:KeyboardEvent):void {
			// cancel keyCode registration
			switch(e.keyCode)
			{
				case Keyboard.UP:	state[0] = 0; break;
				case Keyboard.DOWN:	state[1] = 0; break;
				case Keyboard.LEFT:	state[2] = 0; break;
				case Keyboard.RIGHT:state[3] = 0; break;
			}
		}
		
		private function onKeyDown(e:KeyboardEvent):void {
			// register keyCode
			switch(e.keyCode)
			{
				case Keyboard.UP:	state[0] = e.keyCode; break;
				case Keyboard.DOWN:	state[1] = e.keyCode; break;
				case Keyboard.LEFT:	state[2] = e.keyCode; break;
				case Keyboard.RIGHT:state[3] = e.keyCode; break;
			}
		}

		private function onProcess(e:Event):void {			
			(state[2] != 0 && state[0] != 0) ? (sp.x -= speed / Math.sqrt(2), sp.y -= speed / Math.sqrt(2)): // 左上
			(state[3] != 0 && state[0] != 0) ? (sp.x += speed / Math.sqrt(2), sp.y -= speed / Math.sqrt(2)): // 右上
			(state[2] != 0 && state[1] != 0) ? (sp.x -= speed / Math.sqrt(2), sp.y += speed / Math.sqrt(2)): // 左下
			(state[3] != 0 && state[1] != 0) ? (sp.x += speed / Math.sqrt(2), sp.y += speed / Math.sqrt(2)): // 右下
			(state[0] != 0 && state[1] == 0) ? sp.y-=speed: //上
			(state[0] == 0 && state[1] != 0) ? sp.y+=speed: //下
			(state[2] != 0 && state[3] == 0) ? sp.x-=speed: //左
			(state[2] == 0 && state[3] != 0) ? sp.x+=speed:	0; //右	
		}

	}
		
}
